package com.etrans.web.gps.business.gis.service;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.etrans.egov.base.intf.ObjDriver;
import com.etrans.egov.base.intf.TIntfObjTrack;
import com.etrans.web.gps.base.service.BaseService;
import com.etrans.web.gps.business.gis.domain.SubsectionVO;
import com.etrans.web.gps.business.gis.domain.Track;
import com.etrans.web.gps.business.gis.domain.TrackPlayBack;
import com.etrans.web.gps.util.EgovUtil;
import com.etrans.web.gps.util.map.GpsToGaoDe;

/**
 * 轨迹回放
 * @author jw.chen
 *
 */
@Service
public class TrackPlayBackService extends BaseService {

	@Autowired
	private EgovUtil egovUtil;
	
    /**
     * 查询轨迹
     * 
     * @param vehicleId String 
     * @param starDate String
     * @param endDate String
     * @param merge_seconds Integer
     * @param stop_seconds Integer
     * @return
     */
    public List<TrackPlayBack> selectPlayBackTrack(String vehicleId,String starDate,String endDate,Integer merge_seconds,Integer stop_seconds){
    	DecimalFormat decimalFormat = new DecimalFormat("#.000000");
        long s = System.currentTimeMillis();
        if(null==vehicleId || starDate==null || endDate==null)return null;
        if(merge_seconds==null)merge_seconds=-1;
        if(stop_seconds==null)merge_seconds=-1;
        Map<String,Object> queryParam =  new HashMap<>();
        queryParam.put("i_vehicle_id", vehicleId);
        queryParam.put("i_startTime", starDate);
        queryParam.put("i_endTime", endDate);
        queryParam.put("i_merge_seconds", merge_seconds);
        queryParam.put("i_stop_seconds", stop_seconds);
        List<TrackPlayBack> list = selectList("track.selectPlayBackTrack",queryParam);
        List<HashMap<String,Object>> vehicleList = selectList("track.selectVehicleTerminalKind",queryParam);
        int terminalKind=0;
        if(vehicleList.size()>0){
        	try{
        		terminalKind=Integer.parseInt(vehicleList.get(0).get("kind").toString());
        	}catch(Exception e){
        		
        	}
        	
        }
        int[] strStatus= {0,1,9,10,11,12,13,17,18};
    	int[] strAlarm={26,27,28};
    	String[] strStatusName= "ACC,是否定位,前门,后门,车门,发动机,空调,远光灯,近光灯".split(",");
    	String[] strAlarmName="紧急报警,超速报警,疲劳驾驶".split(",");
        for(int i=0;i<list.size();i++){
        	TrackPlayBack trackPlayBack = list.get(i);
        	double[] latLong = GpsToGaoDe.transform(trackPlayBack.getLatitude()/1000000, trackPlayBack.getLongitude()/1000000);
        	trackPlayBack.setLatitude(Double.parseDouble(decimalFormat.format(latLong[0])));
        	trackPlayBack.setLongitude(Double.parseDouble(decimalFormat.format(latLong[1])));
        	trackPlayBack.setGps_speed(trackPlayBack.getGps_speed()/10);
        	
        	try{
//        		Map<Integer, Boolean> tempMap=egovUtil.decodeStatus(terminalKind, trackPlayBack.getStatus());
        		Map<Integer, Boolean> tempMap= new HashMap<Integer, Boolean>();
            	String vehicleStatus="";
            	for(int j=0;j<strStatus.length;j++){
            	    if(j==0){
            	    	if(tempMap.get(strStatus[j])){
            	    		vehicleStatus=strStatusName[j]+"开";
            			}else{
            				vehicleStatus=strStatusName[j]+"关";
            			}	
            	    }else if(j==1){
            	    	if(tempMap.get(strStatus[j])){
            	    		vehicleStatus=vehicleStatus+","+"精确";
            			}else{
            				vehicleStatus=vehicleStatus+","+"盲区";
            			}
            		}else{
            			if(tempMap.get(strStatus[j])){
            	    		vehicleStatus=vehicleStatus+","+strStatusName[j]+"开";
            			}else{
            				vehicleStatus=vehicleStatus+","+strStatusName[j]+"关";
            			}
            		}
            	}
            	trackPlayBack.setStatus(vehicleStatus);
        	}catch(Exception e){
        		
        	}
        	
        }
        return list;
    }

//    /**
//     * 查询轨迹
//     *
//     * @param queryParam
//     * @return
//     */
//    public Integer selectCount(Map<String,Object> queryParam){
//        long s = System.currentTimeMillis();
//        Integer totalRow = selectOne("track.selectCount",queryParam);
//        return totalRow;
//    }
    
//    /**
//     * 分段合成
//     * 
//     * @param subList
//     * @return
//     */
//    private SubsectionVO composeSubOne(List<SubsectionVO> subList){
//    	if(subList.size()>0 && subList.size()==1){
//    		SubsectionVO vo = subList.get(0);
//    		vo.setDuration_time(DateUtil.getHMBySecond(vo.getDuration()));
//    		return vo;
//    	}else{
//        	SubsectionVO vo = subList.get(0);
//        	for(int i=1;i<subList.size();i++){
//        		SubsectionVO currentVo = subList.get(i);
//        		vo.setDuration(vo.getDuration()+currentVo.getDuration());
//        		vo.setMileage(vo.getMileage()+currentVo.getMileage());
//        		vo.setTired_alarm(vo.getTired_alarm()+currentVo.getTired_alarm());
//        		vo.setRoad_level_speed_alarm_count(vo.getRoad_level_speed_alarm_count()+currentVo.getRoad_level_speed_alarm_count());
//        		vo.setSpeed_alarm(vo.getSpeed_alarm()+currentVo.getSpeed_alarm());
//        		vo.setVehicle_night_alarm(vo.getVehicle_night_alarm()+currentVo.getVehicle_night_alarm());
//        		if(i==(subList.size()-1)){
//        			vo.setEnd_lat(currentVo.getEnd_lat());
//        			vo.setEnd_lon(currentVo.getEnd_lon());
//        			vo.setEnd_time(currentVo.getEnd_time());
//        			vo.setEndposition(currentVo.getEndposition());
//        			vo.setDuration_time(DateUtil.getHMBySecond(vo.getDuration()));
//        		}
//        	}
//        	return vo;
//    	}
//    }
//    /**
//     * 
//     * @param lSubsectionVOs
//     * @return
//     */
//    private List<SubsectionVO> reSortSubSection(List<SubsectionVO> lSubsectionVOs){
//    	if(lSubsectionVOs!=null && lSubsectionVOs.size()>1){
//    		List<SubsectionVO> nList = new ArrayList<SubsectionVO>();
//    		List<SubsectionVO> tempList = new ArrayList<SubsectionVO>();
//    		SubsectionVO preVo = null;
//    		Integer preFlag = null;// 0 停车，1开车
//    		for(int i=0;i<lSubsectionVOs.size();i++){
//    			SubsectionVO vo = lSubsectionVOs.get(i);
//    			// 前后状态一致
//    			if(i==0){
//    				preVo = vo;
//    				preFlag  = vo.getAnalyse_falg();
//    				tempList.add(preVo);
//    			}else{
//    				int between = DateUtil.SecondsBetween(preVo.getEnd_time(),vo.getStart_time());
//    				boolean flag = DateUtil.isSameDate(preVo.getEnd_time(),vo.getStart_time());
//    				// 前后状态一致，并且间隔时间不超过10分钟
//    				 if(preFlag==vo.getAnalyse_falg() && between<600 && flag){
//    					 tempList.add(vo);
//    					 preVo = vo;
//    				 }else{//前后不一致
//    					 //合成一条
//    					 nList.add(composeSubOne(tempList));
//    					 tempList = new ArrayList<>();
//    					 tempList.add(vo);
//    					 preVo = vo;
//    					 preFlag = vo.getAnalyse_falg();
//    				 }
//    			}
//    		}
//    		 nList.add(composeSubOne(tempList));
//    		return nList;
//    	}else{
//    		return lSubsectionVOs;
//    	}
//    }
    
    /**
     * 汇总数据
     * 
     * @param whereMap
     * @return
     */
    public List<SubsectionVO> selectSubSectionTotalByCondition(HashMap<String, Object> whereMap){
    	return selectList("track.selectSubSectionTotalByCondition",whereMap);
    }

    public List<ObjDriver> getHisDriver(String vehicle_no, String start_time,String end_time) throws Exception {
    	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	return egovUtil.getHisDriver(vehicle_no, format.parse(start_time), format.parse(end_time));
    }
    
	public List<Track> getHisTrack(String vehicle_no, String start_time,String end_time) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		List<Track> result = new ArrayList<Track>();
		List<TIntfObjTrack> resTrack = egovUtil.getHisTrack(vehicle_no,format.parse(start_time),format.parse(end_time));
		if(resTrack != null){
			for (TIntfObjTrack objTrack : resTrack) {
				if (objTrack != null) {
					Track track = new Track();
					track.setVehicleNo(objTrack.getVehicleNo());
					track.setVehicleColor(objTrack.getVehicleColor());
					track.setVehicleId(objTrack.getVehicleId());
					track.setLongitudeD(objTrack.getLongitudeD());
					track.setLatitudeD(objTrack.getLatitudeD());
					if (objTrack.getValid()) {
						track.setValidS("定位");
					} else {
						track.setValidS("盲区");
					}
					if (objTrack.getLatitudeD() != 0 && objTrack.getLongitudeD() != 0) {
						double[] gdLatlon = GpsToGaoDe.transform(objTrack.getLatitudeD(), objTrack.getLongitudeD());
						if(gdLatlon != null){
							track.setLatitude(Double.parseDouble(new DecimalFormat("#.000000").format(gdLatlon[0])));
							track.setLongitude(Double.parseDouble(new DecimalFormat("#.000000").format(gdLatlon[1])));
						}
					}
					track.setGpsTimeS(format.format(objTrack.getGpsTime()));
					track.setGpsMileage(objTrack.getMileage());
					track.setGpsSpeedF(objTrack.getGpsSpeed());
					track.setPulseSpeedF(objTrack.getPulseSpeed());
					track.setHead(objTrack.getDirection());
					track.setValid(objTrack.getValid());
					track.setAccStatus(objTrack.getAccON());
					if (objTrack != null && objTrack.getGpsTimeS() != null) {   // 1.开车 2 停车  3离线       4 报警(去掉)
						long diff = System.currentTimeMillis() - objTrack.getGpsTime();
						if (Math.abs(diff) < 1000 * 60 * 10) {
							if (objTrack.getGpsSpeed() > 0) {
								track.setCarStatus(1);
							} else {
								track.setCarStatus(2);
							}
						} else {
							track.setCarStatus(3);
						}
					}
					result.add(track);
				}
			}
		}
		return result;
	}

	public HashMap<String, Object> getDriver(HashMap<String, Object> param) {
		return this.selectOne("monitorMapper.queryDriverInfo", param);
	}
}
